<?php

namespace App\Kuafu\Order\Jobs;

use App\Kuafu\Order\Exceptions\OrderException;
use App\Kuafu\Order\Model\OrderCouponSplitModel;
use App\Kuafu\Order\Service\OrderPayService;
use App\Kuafu\Pay\Exceptions\PayException;
use App\Kuafu\Pay\Model\PayStreamModel;
use App\Kuafu\Pay\Service\PayService;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;

/**
 * 订单未支付自动关闭
 * Class OrderPayPolling
 * @package App\Kuafu\Order\Jobs
 */
class OrderPayPolling implements ShouldQueue
{
    /**
     * php artisan queue:work redis --queue={RMS-API-ORDER-PAY}
     */
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    const QUEUE_NAME = '{RMS-API-ORDER-PAY}';

    /**
     * @var string orderId
     */
    private $orderId;

    /**
     * @var int brandId
     */
    private $brandId;

    /**
     * @var int shopId
     */
    private $shopId;

    /**
     * @var string 支付流水号
     */
    private $payNo;

    /**
     * Create a new job instance.
     *
     * @param $brandId
     * @param $shopId
     * @param $orderId
     * @param $payNo
     * @param int $expiredTime
     */
    public function __construct($brandId, $shopId, $orderId, $payNo)
    {
        $this->brandId = $brandId;
        $this->shopId  = $shopId;
        $this->orderId = $orderId;
        $this->payNo   = $payNo;

        Log::info("order_pay_polling", [
            'brandId' => $brandId,
            'shopId'  => $shopId,
            'orderId' => $orderId,
            'payNo'   => $payNo,
        ]);
    }

    /**
     * Execute the job.
     *
     * @return void
     * @throws OrderException|PayException
     */
    public function handle()
    {
        // 查支付数据是否完成
        $order = new OrderPayService($this->brandId, $this->shopId, $this->orderId);

        // 获取订单情况
        $orderPay = PayService::sQuery($this->payNo);
        Log::info("order_pay_polling order info", [$orderPay]);

        // 获取是否支付成功
        if ($orderPay->payStatus != PayStreamModel::PAY_STATUS_1) {
            $order->cancel();
        }
    }
}
